const adminModel = require('../model/adminModel')
const { getToken, verifyToken } = require('../token')
const {
  SUCCESS_RESPONSE,
  FAIL_RESPONSE,
  PORT,
  PASSWORD_SALT,
} = require('../config/constant')
const md5 = require('md5')
const fs = require('fs')
const { update } = require('lodash')

// 登录请求
exports.login = async (req, res) => {
  // 获得请求体参数
  let { username, password } = req.body

  // 查询数据是否存在
  let findUser = await adminModel.getFindUser(username, password)

  if (findUser.length > 0) {
    // 生成JWT用户登录态(token字符串),返回给前端
    let accessToken = getToken(
      { admin_id: findUser[0].admin_id, username: findUser[0].username },
      '1h'
    )
    let refreshToken = getToken(
      { admin_id: findUser[0].admin_id, username: findUser[0].username },
      '15d'
    )

    res.json(SUCCESS_RESPONSE('登录成功', { accessToken, refreshToken }))
  } else {
    res.json(FAIL_RESPONSE('20002', '用户名或密码错误'))
  }
}

// 获取管理员信息
exports.adminInfo = async (req, res) => {
  let admin_id = req.admin_id
  let data = await adminModel.getAdminInfo(admin_id)
  data[0].avatar = `http://127.0.0.1:${PORT}/` + data[0].avatar
  res.json(SUCCESS_RESPONSE('获取用户信息成功', { ...data[0] }))
}

// 刷新token
exports.refreshToken = async (req, res) => {
  let { refreshToken } = req.body

  // 1. 验证refreshToken中的有效期
  let userInfo = verifyToken(refreshToken)

  if (userInfo === false) {
    // refreshToken失效了
    res.status(401).json({ msg: '用户refreshToken刷新失败', code: 'A0231' })
    return
  }
  // 2. 获取refreshToken中的用户信息,要去数据库查询最新的用户信息
  let result = await adminModel.getAdminInfoById(userInfo.admin_id)
  if (result.length > 0) {
    let accessToken = getToken(
      { admin_id: result[0].admin_id, username: result[0].username },
      '1h'
    )

    // 3. 重新再生成新token并返回给前端
    res.json(SUCCESS_RESPONSE('刷新token成功', { accessToken, refreshToken }))
  } else {
    res.json(FAIL_RESPONSE('20003', '用户信息有误'))
  }
}

// 获取管理员数据
exports.adminData = async (req, res) => {
  let result = await adminModel.getAdminData()

  res.json(SUCCESS_RESPONSE('获取管理员信息成功', result))
}

// 文件上传
exports.upload = (req, res) => {
  // console.log(req.body) //接收文本信息
  // console.log(req.file) //接收文件信息
  // 判断是否有文件上传
  if (req.file) {
    // 进行文件的重命名即可 fs.rename
    let { originalname, destination, filename } = req.file
    let dotIndex = originalname.lastIndexOf('.')
    let ext = originalname.substring(dotIndex)
    let oldPath = `${destination}${filename}`
    let newPath = `${destination}${filename}${ext}`
    fs.rename(oldPath, newPath, async (err) => {
      if (err) {
        throw err
      }
      res.json(
        SUCCESS_RESPONSE('上传文件成功', {
          path: `${newPath}`,
          server_url: `http://127.0.0.1:${PORT}/`,
        })
      )
    })
  } else {
    res.json(FAIL_RESPONSE('20004', '没有文件'))
  }
}

// 更新头像
exports.uploadAvatarData = async (req, res) => {
  let admin_id = req.admin_id
  let { avatar } = req.body
  await adminModel.uploadAvatar(admin_id, avatar)
  res.json(SUCCESS_RESPONSE('更新头像成功'))
}

// 修改密码
exports.changePasswordData = async (req, res) => {
  let admin_id = req.admin_id
  let { oldPassword, newPassword } = req.body
  oldPassword = md5(oldPassword + PASSWORD_SALT)
  console.log('oldPassword=>', oldPassword)

  // 确定密码是否正确
  let adminInfo = await adminModel.getAdminInfoById(admin_id)
  console.log('adminInfo[0].password=>', adminInfo[0].password)
  if (oldPassword !== adminInfo[0].password) {
    // 不正确
    res.json(FAIL_RESPONSE('20005', '原密码错误'))
    return
  }
  // 正确
  // 修改数据库密码
  newPassword = md5(newPassword + PASSWORD_SALT)
  console.log('newPassword=>', newPassword)
  await adminModel.changePassword(admin_id, newPassword)
  res.json(SUCCESS_RESPONSE('修改密码成功'))
}

// 获取系统图标和标题
exports.getLogoInfo = async (req, res) => {
  let logoInfo = await adminModel.logoInfo()
  logoInfo.logo_img = `http://127.0.0.1:${PORT}/` + logoInfo.logo_img
  res.json(SUCCESS_RESPONSE('获取系统图标和标题成功', logoInfo))
}

// 更新系统标题
exports.updateLogoTitle = async (req, res) => {
  let { logoTitle } = req.body
  await adminModel.updateTitle(logoTitle)
  res.json(SUCCESS_RESPONSE('更新系统标题成功'))
}

// 更新系统图标
exports.updateLogoImg = async (req, res) => {
  let { logoImg } = req.body
  console.log('~~~~~~~', logoImg)
  await adminModel.updateImg(logoImg)
  res.json(SUCCESS_RESPONSE('更新系统图标成功'))
}
